package com.tjshop.android;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.actionbarsherlock.app.ActionBar;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.toolbox.StringRequest;
import com.tjshop.android.adapter.GoodsListAdapter;
import com.tjshop.android.adapter.SearchHistoryAdapter;
import com.tjshop.android.constants.UrlConfigs;
import com.tjshop.android.model.tj.json.Goods;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 活动详情界面。
 * 
 * @author FIMH
 * @since 2015-01-03
 */
public class SearchActivity extends BaseActivity implements
		View.OnClickListener {

	String[] history;
	
	SearchHistoryAdapter historyAdapter;
	
	
	
	ImageView back;
	
	TextView searchTv;
	
	EditText searchInput;
	
	ListView resutListView;
	
	LinearLayout cleanAll;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		findViewById(R.id.outer).getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){


		    @Override
		    public void onGlobalLayout(){
		 

		       //比较Activity根布局与当前布局的大小
		        int heightDiff = findViewById(R.id.outer).getRootView().getHeight()- findViewById(R.id.outer).getHeight();
		        if(heightDiff >100){


		             }else{
findViewById(R.id.historylistview).setVisibility(View.GONE);

		       }
		     }
		});
		cleanAll = (LinearLayout) findViewById(R.id.cleanAll);
		cleanAll.setOnClickListener(this);
		resutListView = (ListView) findViewById(R.id.keywordListview);
		searchTv = (TextView) findViewById(R.id.common_title_bar_right_icon);
		searchTv.setOnClickListener(this);
		searchInput = (EditText) findViewById(R.id.fragment_home_title_bar_search);
		back = (ImageView) findViewById(R.id.common_title_bar_left_icon);
		back.setOnClickListener(this);
		searchInput.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View arg0) {
					findViewById(R.id.historylistview).setVisibility(View.VISIBLE);
				}
			});
		
	}

	@Override
	protected void onResume() {
		getHistory();
		super.onResume();
	}
	private void getHistory(){
		// 获取搜索记录文件内容
				SharedPreferences sp = getSharedPreferences("search_history", 0);
				String h = sp.getString("history", "");

				// 用逗号分割内容返回数组
				history = h.split(",");
				
				if (history .length == 1 && history[0].equals("")) {
					history = new String[0];
				}
				historyAdapter = new SearchHistoryAdapter(getApplicationContext(),history);
	
				initPopWindow();
	}
	
	private void cleanHistory() {
		// 获取搜索框信息
				String text = searchInput.getText().toString();
				SharedPreferences mysp = getSharedPreferences("search_history", 0);
				

				// 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
					SharedPreferences.Editor myeditor = mysp.edit();
					myeditor.remove("history");
					myeditor.commit();
					getHistory();
	}
	public void save() {
		// 获取搜索框信息
		String text = searchInput.getText().toString();
		SharedPreferences mysp = getSharedPreferences("search_history", 0);
		String old_text = mysp.getString("history", "");
		
		// 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
		StringBuilder builder = new StringBuilder(old_text);
		builder.append(text + ",");

		// 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
		if (!old_text.contains(text + ",")) {
			SharedPreferences.Editor myeditor = mysp.edit();
			myeditor.putString("history", builder.toString());
			myeditor.commit();
		}
		getHistory();
		

	}
	class MyAdapter extends BaseAdapter {
		private Context context;
		private String[] keywords;

		public MyAdapter(Context context, String[] keywords) {
			this.context = context;
			this.keywords = keywords;
		}

		@Override
		public int getCount() {
			return keywords.length / 3 + (keywords.length % 3 == 0 ? 0 : 1);
		}

		@Override
		public Object getItem(int arg0) {
			return arg0;
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup arg2) {

			if (convertView == null) {
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_search_keyword, null);
			}

			TextView k1 = (TextView) convertView
					.findViewById(R.id.left_keyword);
			k1.setOnClickListener(listener);
			TextView k2 = (TextView) convertView
					.findViewById(R.id.middle_keyword);
			k2.setOnClickListener(listener);
			TextView k3 = (TextView) convertView
					.findViewById(R.id.right_keyword);
			k3.setOnClickListener(listener);
			TextView[] t = new TextView[] { k1, k2, k3 };
			int startIndex = 3 * position;

			for (int i = startIndex, j = 0; j < 3 & i < keywords.length; j++, i++) {
				t[j].setText(keywords[i]);
				t[j].setVisibility(View.VISIBLE);
			}

			return convertView;
		}

		OnClickListener listener = new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				if (arg0 instanceof TextView) {
					search(((TextView) arg0).getText().toString());
				}
			}
		};

	}

	EditText search;

	public void updateCustomActionBarView() {
		// 不显示返回按键与title
		ActionBar actionBar = getSupportActionBar();
		getSupportActionBar().setDisplayShowHomeEnabled(false);

		View v = LayoutInflater.from(this).inflate(R.layout.inc_search_bar,
				null);
		com.actionbarsherlock.app.ActionBar.LayoutParams params = new com.actionbarsherlock.app.ActionBar.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		getSupportActionBar().setCustomView(v, params);

		ImageView back = (ImageView) v.findViewById(R.id.action_item_return);
		back.setOnClickListener(this);

		search = (EditText) v.findViewById(R.id.fragment_home_title_bar_search);

		ImageView searchBtn = (ImageView) v
				.findViewById(R.id.common_title_bar_right_icon);
		searchBtn.setOnClickListener(this);
		actionBar.setDisplayShowCustomEnabled(true);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.common_title_bar_left_icon: // 首页titlebar的城市
			finish();
			break;
		case R.id.common_title_bar_right_icon:
			
			String txt = searchInput.getText().toString();
			if (txt.equals("")) {
				Toast.makeText(getApplicationContext(), "请输入要搜索的内容",
						Toast.LENGTH_SHORT).show();
			} else {
				save();
				search(txt);
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						findViewById(R.id.historylistview).setVisibility(View.GONE);
					}
				});
			}
			break;
		case R.id.cleanAll:
			cleanHistory();
			break;

		}
	}
	
	ArrayList<Goods> goodsList = new ArrayList<Goods>();

	private GoodsListAdapter mSimpleAdapter;
	private void search(String string) {
//		Bundle b = new Bundle();
//		b.putString("keyword", string);
//
//		// TODO 打开CategoryDetailActivity，其实应该传递一些必要的参数过去
//		Intent intent = new Intent();
//		intent.putExtras(b);
//		intent.setClass(this, GoodsListActivity.class);
//		startActivity(intent);
		
		mProgressDialog.show("搜索中", true, false);
		goodsList = new ArrayList<Goods>();
		StringRequest stringRequest = new StringRequest(Method.GET,
				UrlConfigs.URL_GOODS_LIST + "?key=" + string ,
				new Response.Listener<String>() {
					

					@Override
					public void onResponse(String response) {
						JSONArray jsonU;
						try {
							JSONObject obj = new JSONObject(response);
							if (obj.getInt("r") == 0) {
								jsonU = obj.getJSONArray("s");
								// jsonU = new JSONArray(response);
								for (int i = 0; i < jsonU.length(); i++) {
									Goods g = new Goods();
									g.parse(jsonU.getJSONObject(i));
									goodsList.add(g);
								}
								Message message = new Message();
								message.what = 2;
								mHandler.sendMessage(message);
							} else {
								Message message = new Message();
								message.what = 1;
								mHandler.sendMessage(message);
							}

						} catch (JSONException e) {
							Message message = new Message();
							message.what = 1;
							mHandler.sendMessage(message);
							e.printStackTrace();
						}

					}
				}, new Response.ErrorListener() {

					@Override
					public void onErrorResponse(VolleyError error) {
						Message message = new Message();
						message.what = 1;
						mHandler.sendMessage(message);

					}

				});

		mQueue.add(stringRequest);
	}

	public void updateHomeCity(String text) {
		TextView cityText = (TextView) getSupportActionBar().getCustomView()
				.findViewById(R.id.common_title_bar_text);
		if (cityText != null) {
			cityText.setText(text);
		}
	}
//	PopupWindow popupWindow;
private void initPopWindow(){
    	ListView listView = (ListView) findViewById(R.id.list);
    	listView.setAdapter(historyAdapter);
    	listView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, final int arg2,
					long arg3) {
				search(history[arg2]);
				
				runOnUiThread(new Runnable() {
					
					@Override
					public void run() {
						searchInput.setText(history[arg2]);
						findViewById(R.id.historylistview).setVisibility(View.GONE);
					}
				});
			}
		});
    }

@Override
public boolean handleMessage(Message message) {
	switch (message.what) {
	case 1:
		mProgressDialog.dismiss();
		Toast.makeText(getApplicationContext(), "没有相关商品!", Toast.LENGTH_SHORT).show();
		initResultView();
		break;
	case 2:
		mProgressDialog.dismiss();
		initResultView();
		break;
	default:
		break;
	}
	return false;
}

private void initResultView() {
	mSimpleAdapter = new GoodsListAdapter(getApplicationContext(), goodsList, LayoutInflater.from(getApplicationContext()));
	resutListView.setAdapter(mSimpleAdapter);
	// 设置item点击的监听器
	resutListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1,
				int arg2, long arg3) {
			 Intent intent = new Intent(getApplicationContext(),
			 GoodsDetailActivity.class);
			 intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			 intent.putExtra("gId",goodsList.get(arg2).getGoods_id());
			 getApplicationContext().startActivity(intent);
		}
	});
}
}
